package com.zsjp.alc.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

public class ParseError {
	private static DocumentBuilderFactory dbFactory = null;
	private static DocumentBuilder db = null;
	private static Document document = null;
	private static Map<String, ErrorMessage1> errorMap = null;
	static {
		try {
			dbFactory = DocumentBuilderFactory.newInstance();
			db = dbFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 用DOM方式读取xml文件
	 * 
	 * @author lune
	 */

	public static Map<String, ErrorMessage1> getErrorMap(String fileName) throws Exception {

		final Map<String, ErrorMessage1> errorMap = new HashMap<String, ErrorMessage1>();
		// 将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
		document = db.parse(fileName);
		// 按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
		NodeList errorList = document.getElementsByTagName("error");
		// 遍历books
		for (int i = 0; i < errorList.getLength(); i++) {
			ErrorMessage1 error = new ErrorMessage1();
			// 获取第i个ErrorMessage结点
			org.w3c.dom.Node node = errorList.item(i);
			// 获取第i个errorMessage的所有属性
			NamedNodeMap namedNodeMap = node.getAttributes();
			// 获取已知名为id的属性值
			String id = namedNodeMap.getNamedItem("id").getTextContent();// System.out.println(id);
			error.setErrorCode(id);
			// 获取error结点的子节点
			NodeList cList = node.getChildNodes();// System.out.println(cList.getLength());9
			System.out.println(cList.getLength());
			// 将一个error里面的属性加入数组
			ArrayList<String> contents = new ArrayList<>();
			for (int j = 1; j < cList.getLength(); j += 2) {
				org.w3c.dom.Node cNode = cList.item(j);
				String content = cNode.getFirstChild().getTextContent();
				contents.add(content.trim());
			}

			error.setDescription(contents.get(0));
			error.setSuggestion(contents.get(1));
			errorMap.put(id, error);
		}
		return errorMap;

	}
	/*
	 * public static void main(String[] args){ String fileName =
	 * "src\\main\\java\\com\\zsjp\\alc\\test\\error.xml"; try { Map<String,
	 * ErrorMessage> errorMap= ReadxmlByDom.getErrorMap(fileName); ErrorMessage
	 * error = errorMap.get("10000001"); System.out.println(error); } catch
	 * (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
	 * }
	 */
}
